#include <iostream>
#include <string>
#include <string.h>
#include <cerrno>
#include <unistd.h>
#include "Thread.hpp"

// 网路编程常用套接字
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
// 声明区
class ThreadData;

void Usage(const std::string &s);
std::string PrintAddr(std::string &ip, uint16_t &port);
bool VisitServer(std::string &server_ip, uint16_t &server_port, int *count);

#define RETRY_COUNT 5

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }
    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);

    int count = 1;
    while (count <= RETRY_COUNT)
    {
        // 客户端访问服务
        bool result = VisitServer(ip, port, &count); // 服务的返回值，true正常退出

        if (result == true)
        {
            break;
        }
        else // false需要重连
        {
            sleep(1);
            std::cout << "server offline, retrying..., count: " << count << std::endl;
            count++;
        }
    }
    // 重连次数限制
    if (count >= RETRY_COUNT)
    {
        std::cout << "server offline, client exit finally" << std::endl;
    }
}

// 实现区

class ThreadData
{
public:
    ThreadData(const struct sockaddr_in &addr, const int &sock_fd)
        : _addr(addr), _sock_fd(sock_fd) {}
    ~ThreadData() {}
    const struct sockaddr_in &Addr() const { return _addr; }
    const int &SockFd() const { return _sock_fd; }

private:
    struct sockaddr_in _addr;
    int _sock_fd;
};

void Usage(const std::string &s)
{
    std::cout << "warning: illegal usage!" << std::endl;
    std::cout << "please input as this: " << s.c_str() << " server_ip server_port" << std::endl;
}

std::string PrintAddr(std::string &ip, uint16_t &port) // 返回
{
    std::string addr;
    addr = "[";
    addr += ip;
    addr += ":";
    addr += std::to_string(port);
    addr += "]";
    return addr;
}

// 客户端访问服务器
bool VisitServer(std::string &server_ip, uint16_t &server_port, int *count)
{

    // 创建套接字
    int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (sock_fd < 0)
    {
        std::cout << "falied to run socket" << std::endl;
        return false;
    }

    // 绑定服务器
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    inet_pton(AF_INET, server_ip.c_str(), &server.sin_addr);
    // server.sin_addr.s_addr = inet_addr(server_ip.c_str());

    // TCP链接服务器
    if (connect(sock_fd, (struct sockaddr *)&server, sizeof(server)) < 0)
    {
        std::cout << "failed to run connect" << std::endl;
        return false;
    }

    // 输出型参数
    *count = 1; // 重置更新数目

    // 确认是否获取服务器服务
    std::string link;
Again:
    std::cout << "Visit to Server: yes/no ?" << std::endl;
    std::cout << "please enter# ";
    std::getline(std::cin, link);

    if (link == "yes")  // 客户端向服务器进行服务的交互
    {
        char server_list[1024];

        // 客户端跟服务器的通信
        ssize_t n = read(sock_fd, server_list, sizeof(server_list));
        if (n > 0)
        {
            server_list[n] = 0;
            std::cout << "Service list: " << server_list << std::endl;
        }
        else if (n == 0)
        {
            std::cout << "server quit" << std::endl;
            return false;
        }

    Message:

        std::string message;
        std::cout << "input: service/quit ?" << std::endl;
        std::cout << "please select# ";
        std::getline(std::cin, message);

        // client响应service

        // translate模块
        if (message == "translate")
        {
            // 先写入选择的服务
            write(sock_fd, message.c_str(), message.size());
            std::cout << "please enter a word: ";
            std::getline(std::cin, message);
            // 写入待翻译的单词
            ssize_t m = write(sock_fd, message.c_str(), message.size());
            if (m > 0)
            {
                char chinese[1024];
                ssize_t i = read(sock_fd, chinese, sizeof(chinese) - 1);
                if (i > 0)
                {
                    chinese[i] = 0;
                    printf("the word: [%s] translate to [%s]\n", message.c_str(), chinese);
                }
                else if (i == 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                std::cout << "write error" << std::endl;
                return false;
            }
        }
        // ping模块
        else if (message == "ping")
        {
            write(sock_fd, message.c_str(), message.size());

            char buffer[1024];
            ssize_t i = read(sock_fd, buffer, sizeof(buffer) - 1);
            if (i > 0)
            {
                buffer[i] = 0;
                std::cout << buffer << std::endl;
            }
            else if (i == 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        // transform模块
        else if (message == "transform")
        {
            // 先写入选择的服务
            write(sock_fd, message.c_str(), message.size());
            std::cout << "please enter a word: ";
            std::getline(std::cin, message);
            // 写入待翻译的单词
            ssize_t m = write(sock_fd, message.c_str(), message.size());
            if (m > 0)
            {
                char transform[1024];
                ssize_t i = read(sock_fd, transform, sizeof(transform) - 1);
                if (i > 0)
                {
                    transform[i] = 0;
                    printf("the word: [%s] transform to [%s]\n", message.c_str(), transform);
                }
                else if (i == 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                std::cout << "write error" << std::endl;
                return false;
            }
        }
        // 发送退出信息给服务器
        else if (message == "quit")
        {
            return true;
        }
        // 使用不支持的服务，重新输入
        else
        {
            printf("Service: [%s] no supported, please input the tasks provided\n", message.c_str());
            goto Message;
        }
    }
    else if (link == "no")
    {
        return true;
    }
    else
    {
        std::cout << "illegal input, please input: yes or no " << std::endl;
        goto Again;
    }

    close(sock_fd);
    return true;
}
